package models

import (
	"api/go-demo/utils"

	"github.com/jinzhu/gorm"
)

type PerMenu struct {
	MenuId       int    `gorm:"column:menu_id" json:"menu_id"`
	MenuName     string `gorm:"column:menu_name" json:"menu_name"`
	MenuStatus   string `gorm:"column:menu_status" json:"menu_status"`
	MenuType     int    `gorm:"column:menu_type" json:"menu_type"`
	MenuOrderNo  int    `gorm:"column:menu_order_no" json:"menu_order_no"`
	MenuParentId int    `gorm:"column:menu_parent_id" json:"menu_parent_id"`
	MenuUrl      string `gorm:"column:menu_url" json:"menu_url"`
	SysID        int    `gorm:"column:sys_id" json:"sys_id"`
}

func (menu *PerMenu) TableName() string {
	return "per_menu"
}

//查询菜单树
func FindPerMenuTree(logInfo *utils.LogInfo, db *gorm.DB, req *utils.FindPerMenuTreeReq) ([]*utils.JsonTreeNodeResp, error) {
	log := logInfo.NewLog("models.FindAuthorityResourceArry")
	log.DebugDB("查询资源列表", "parent_id:%v", req.ParentId)
	nodeList := make([]*utils.JsonTreeNodeResp, 0)
	t := &PerMenu{}
	db = db.Table(t.TableName())
	menuArry := make([]*PerMenu, 0)
	if err := db.Find(&menuArry).Error; err != nil {
		log.Error(utils.ErrDB, "查询菜单树异常", err)
		if err == gorm.ErrRecordNotFound {
			return nodeList, nil
		}
		return nodeList, err
	}
	//拼装为jsonnode

	for _, menu := range menuArry {
		node := &utils.JsonTreeNodeResp{}
		node.Id = menu.MenuId
		node.Label = menu.MenuName
		node.ParentId = menu.MenuParentId
		nodeList = append(nodeList, node)
	}
	//生成父节点 - 子节点数组 map
	parentIdListMap := make(map[int][]*utils.JsonTreeNodeResp, 0)
	for _, node := range nodeList {
		child, ok := parentIdListMap[node.ParentId]
		if ok {
			child = append(child, node)
		} else {
			child = make([]*utils.JsonTreeNodeResp, 0)
			child = append(child, node)
		}
		parentIdListMap[node.ParentId] = child
	}
	//上下级关系维护
	findIdMap := make(map[int]int, 0)
	for _, mv := range parentIdListMap {
		for _, chid := range mv {
			findId := chid.Id
			if childs, ok := parentIdListMap[findId]; ok {
				findIdMap[findId] = 1
				chid.Children = childs
			}
		}
	}
	resp := make([]*utils.JsonTreeNodeResp, 0)
	for mk, mv := range parentIdListMap {
		if _, ok := findIdMap[mk]; !ok {
			for _, child := range mv {
				resp = append(resp, child)
			}
		}
	}
	return resp, nil
}
